package com.x.provider.customer.service.customer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.x.provider.customer.mapper.CustomerSessionMapper;
import com.x.provider.customer.model.domain.customer.CustomerSession;
import com.x.provider.customer.model.query.customer.CustomerSessionQuery;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author: liushenyi
 * @date: 2022/08/16/16:57
 */
@Service
public class CustomerSessionServiceImpl implements CustomerSessionService {

    private final CustomerSessionMapper customerSessionMapper;

    public CustomerSessionServiceImpl(CustomerSessionMapper customerSessionMapper){
        this.customerSessionMapper = customerSessionMapper;
    }

    @Override
    public void saveLoginSession(Long customerId, String lastIpAddress) {
        CustomerSession customerSession = get(CustomerSessionQuery.builder().customerId(customerId).build());
        if (customerSession == null){
            customerSession = CustomerSession.builder().customerId(customerId).build();
        }
        customerSession.setLastIpAddress(lastIpAddress);
        customerSession.setLastLoginDateUtc(new Date());
        customerSession.setLastActivityDateUtc(new Date());
        saveCustomerSession(customerSession);
    }

    @Async
    @Override
    public void saveActiveSession(Long customerId, String lastIpAddress) {
        CustomerSession customerSession = get(CustomerSessionQuery.builder().customerId(customerId).build());
        if (customerSession == null){
            return;
        }
        customerSession.setLastIpAddress(lastIpAddress);
        customerSession.setLastActivityDateUtc(new Date());
        saveCustomerSession(customerSession);
    }

    private void saveCustomerSession(CustomerSession customerSession){
        if (customerSession.getId() != null){
            customerSessionMapper.updateById(customerSession);
            return;
        }
        customerSessionMapper.insert(customerSession);
    }

    private CustomerSession get(CustomerSessionQuery query){
        return customerSessionMapper.selectOne(build(query));
    }

    private LambdaQueryWrapper<CustomerSession> build(CustomerSessionQuery customerSessionQuery){
        LambdaQueryWrapper<CustomerSession> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (customerSessionQuery.getCustomerId() != null){
            lambdaQueryWrapper = lambdaQueryWrapper.eq(CustomerSession::getCustomerId, customerSessionQuery.getCustomerId());
        }
        return lambdaQueryWrapper;
    }

    private void prepare(CustomerSession customerSession){

    }
}
